<template>
  <div class="upload-container">
    <h2 class="upload-title">文件上传</h2>
    <div class="directory-upload-section">
      <h3 class="section-title">目录上传</h3>
      <div class="directory-inputs">
        <el-input
          v-model="sourceDir"
          placeholder="源目录路径"
          class="directory-input"
        />
        <el-input
          v-model="targetDir"
          placeholder="目标目录路径"
          class="directory-input"
        />
      </div>
      <div class="directory-buttons">
        <el-button type="primary" @click="uploadNginxDir">一键上传Nginx目录</el-button>
        <el-button @click="uploadCustomDir">上传自定义目录</el-button>
        <el-button @click="validateDirs">验证目录</el-button>
        <el-button @click="clearDirInputs">清空输入</el-button>
        <el-button @click="refreshFileList">刷新列表</el-button>
        <el-button type="danger" @click="clearTargetDir">清空目标目录</el-button>
      </div>
    </div>
    <div class="upload-area">
      <el-upload
        class="upload-demo"
        drag
        action="http://192.168.18.151:8097/api/upload"
        :on-success="handleSuccess"
        :on-error="handleError"
        multiple
      >
        <el-icon class="el-icon--upload"><upload /></el-icon>
        <div class="el-upload__text">
          <em>点击或拖拽文件到此处上传</em>
        </div>
        <div class="el-upload__tip mt-2">
          支持单文件或多文件上传，文件大小不超过100MB
        </div>
      </el-upload>
    </div>
    <div class="file-list" v-if="uploadedFiles.length > 0">
      <h3>已上传文件</h3>
      <ul>
        <li v-for="file in uploadedFiles" :key="file.id">
          <span>{{ file.name }}</span>
          <span class="file-size">({{ formatSize(file.size) }})</span>
          <el-button type="primary" size="mini" @click="downloadFile(file)">下载</el-button>
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElUpload, ElIcon } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'
import {
  wcao,
  post,
  get
} from "@/http";

const uploadedFiles = ref([])
const sourceDir = ref('D:\\opt\\nginx\\nginx-1.28.0\\html')
const targetDir = ref('D:\\AppData')

function handleSuccess(response, uploadFile) {
  if (response.success) {
    uploadedFiles.value.push({
      id: response.data.id,
      name: uploadFile.name,
      size: uploadFile.size,
      url: response.data.url
    })
    ElMessage.success('文件上传成功')
  } else {
    ElMessage.error('文件上传失败: ' + response.message)
  }
}

function handleError(error) {
  ElMessage.error('上传出错: ' + error.message)
}

function formatSize(bytes) {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

function downloadFile(file) {
  window.open(file.url, '_blank')
}

// 目录上传功能
function uploadNginxDir() {
  // 使用预设的Nginx目录
  sourceDir.value = 'D:\\opt\\nginx\\nginx-1.28.0\\html'
  targetDir.value = 'D:\\AppData'
  uploadDirectory()
}

function uploadCustomDir() {
  if (!sourceDir.value || !targetDir.value) {
    ElMessage.warning('请填写源目录和目标目录')
    return
  }
  uploadDirectory()
}

function uploadDirectory() {
  ElMessage.info(`正在上传目录: ${sourceDir.value}`)
  post('/api/upload/directory', {
    sourceDir: sourceDir.value,
    targetDir: targetDir.value
  })
  .then(response => {
    if (response.success) {
      ElMessage.success(`目录上传成功，共上传${response.data.fileCount}个文件`)
      fetchUploadedFiles()
    } else {
      ElMessage.error(`上传失败: ${response.message}`)
    }
  })
  .catch(error => {
    ElMessage.error(`请求失败: ${error.message || '网络错误'}`)
  })
}

function validateDirs() {
  if (!sourceDir.value || !targetDir.value) {
    ElMessage.warning('请填写源目录和目标目录')
    return
  }
  ElMessage.info('正在验证目录...')
  post('/api/validate/directory', {
    sourceDir: sourceDir.value,
    targetDir: targetDir.value
  })
  .then(response => {
    if (response.success) {
      ElMessage.success('目录验证通过')
    } else {
      ElMessage.error(`验证失败: ${response.message}`)
    }
  })
  .catch(error => {
    ElMessage.error(`验证请求失败: ${error.message || '网络错误'}`)
  })
}

function clearDirInputs() {
  sourceDir.value = ''
  targetDir.value = ''
}

function refreshFileList() {
  ElMessage.info('正在刷新文件列表...')
  fetchUploadedFiles()
}

function clearTargetDir() {
  if (!targetDir.value) {
    ElMessage.warning('请填写目标目录')
    return
  }
  ElMessage.confirm(
    `确定要清空目录: ${targetDir.value}吗？此操作不可恢复！`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
  .then(() => {
    post('/api/clear/directory', {
      targetDir: targetDir.value
    })
    .then(response => {
      if (response.success) {
        ElMessage.success('目录清空成功')
        fetchUploadedFiles()
      } else {
        ElMessage.error(`清空失败: ${response.message}`)
      }
    })
    .catch(error => {
      ElMessage.error(`请求失败: ${error.message || '网络错误'}`)
    })
  })
  .catch(() => {
    ElMessage.info('已取消清空操作')
  })
}

// 获取已上传文件列表
function fetchUploadedFiles() {
  get('/api/files/list')
    .then(response => {
      if (response.success) {
        uploadedFiles.value = response.data.files
      } else {
        ElMessage.error(`获取文件列表失败: ${response.message}`)
      }
    })
    .catch(error => {
      console.error('获取文件列表请求失败:', error)
    })
}

// 组件挂载时获取文件列表
onMounted(() => {
  fetchUploadedFiles()
})
</script>

<style scoped>
.directory-upload-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.section-title {
  margin-bottom: 15px;
  font-size: 18px;
  color: #333;
}

.directory-inputs {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.directory-input {
  flex: 1;
}

.directory-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

@media (max-width: 768px) {
  .directory-inputs {
    flex-direction: column;
  }
  .directory-buttons {
    justify-content: center;
  }
}
.upload-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 32px;
}

.upload-title {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 24px;
}

.upload-area {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 40px 20px;
  text-align: center;
  margin-bottom: 32px;
}

.file-list {
  margin-top: 24px;
}

.file-list h3 {
  font-size: 18px;
  margin-bottom: 16px;
}

.file-list ul {
  list-style: none;
  padding: 0;
}

.file-list li {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border-bottom: 1px solid #eee;
}

.file-size {
  color: #666;
  margin-left: 8px;
}
</style>